<template>
  <n-layout class="center-container" has-sider position="absolute">
    <n-drawer v-model:show="showMenuDrawer" :width="200" placement="left" class="menu-drawer" to=".center-container">
      <n-drawer-content>
        <n-layout-sider :native-scrollbar="false" class="h-full" :width="200">
          <div :class="['sider-logo', 'h-[54px]', { 'bg-primary': mainStore.theme === 'light' }]">
            <div class="logo-content flex items-center justify-center">
              <n-text class="text-lg">授权系统</n-text>
            </div>
          </div>
          <n-menu :indent="30" :options="centerData.menuOptions" :value="$route.name" @update:value="switchMenu"
            :watch-props="['defaultExpandedKeys']" />
        </n-layout-sider>
      </n-drawer-content>
    </n-drawer>

    <n-layout-sider :native-scrollbar="false" :width="248" v-show="showMenu">
      <div :class="['sider-logo', 'h-[54px]', { 'bg-primary': mainStore.theme === 'light' }]">
        <div class="logo-content flex items-center justify-center">
          <n-text class="text-lg">授权系统</n-text>
        </div>
      </div>
      <n-menu :value="$route.name" :watch-props="['defaultExpandedKeys']" :options="centerData.menuOptions" @update:value="switchMenu" />
    </n-layout-sider>

    <n-layout :native-scrollbar="false" class="main-layout">
      <div :class="['header-container', { 'bg-primary': mainStore.theme === 'light' }]">
        <n-layout-header :class="['xs:py-2.5', 'xs:px-4', { 'bg-primary': mainStore.theme === 'light' }]">
          <n-space align="center">
            <n-button class="flex items-center" v-if="!showMenu" text @click="showMenuDrawer = !showMenuDrawer">
              <n-icon :component="ListOutline" color="#ffffff" size="26" />
            </n-button>
            <n-button class="flex items-center" text @click="$router.push('/redirect')" :disabled="mainStore.pageLoading">
              <n-icon :component="SyncOutline" color="#ffffff" size="26" />
            </n-button>
            <div class="flex items-center">
              <n-text class="text-base text-white">{{ $route.meta.title }}</n-text>
            </div>
          </n-space>
          <div class="flex items-center">
            <n-switch v-model:value="mainStore.theme" checked-value="dark" @update:value="mainStore.setTheme"
              unchecked-value="light" :rail-style="({ checked }) => ({ background: checked ? '#424245' : '#cccccc' })">
              <template #checked-icon>
                <n-icon :component="MoonOutline" />
              </template>
              <template #unchecked-icon>
                <n-icon :component="SunnyOutline" />
              </template>
            </n-switch>
            <n-dropdown :options="centerData.userOptions" :width="150" class="rounded" placement="bottom-end" size="large"
              to=".center-container" trigger="click" @select="selectUserMenu">
              <n-avatar class="cursor-pointer ml-3" round>{{ userStore.userInfo?.username }}</n-avatar>
            </n-dropdown>
          </div>
        </n-layout-header>
      </div>
      <n-layout-content class="main-content xs:mt-14 s:mt-14 mb-0">
        <div class="content-container xs:p-3 s:p-6 mx-auto">
          <router-view />
        </div>
      </n-layout-content>
    </n-layout>
  </n-layout>

  <n-drawer v-model:show="personalState.showPersonalDrawer" :width="400" to=".center-container">
    <n-drawer-content title="个人中心" closable>
      <n-text class="n-h4 text-gray-400" depth="3">修改密码</n-text>
      <n-form class="mt-4" ref="editPwdFormRef" :model="personalState.editPasswordForm"
        :rules="personalState.passwordRules">
        <n-form-item label="旧密码" path="password">
          <n-input v-model:value="personalState.editPasswordForm.password" size="large" placeholder="请输入旧密码" />
        </n-form-item>
        <n-form-item label="新密码" path="newPassword">
          <n-input v-model:value="personalState.editPasswordForm.newPassword" size="large" placeholder="请输入新密码" />
        </n-form-item>
        <n-space justify="end">
          <n-button type="primary" size="large" @click="submitEditPassword" :loading="personalState.changing">修改</n-button>
        </n-space>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup>
import { h, onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { menuRoutes } from '@/router/modules'
import { useMainStore, useUserStore } from '@/store'
import { NAvatar, NIcon } from 'naive-ui'
import { changePass } from '@api/userApi'
import {
  HomeOutline,
  KeyOutline,
  SyncOutline,
  ListOutline,
  SunnyOutline,
  MoonOutline,
  PersonCircleOutline,
  LogOutOutline
} from '@vicons/ionicons5'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const mainStore = useMainStore()
const router = useRouter()

const renderIcon = (icon) => {
  return () => {
    return h(NIcon, { size: 24 }, {
      default: () => h(icon)
    });
  };
};

const centerData = reactive({
  menuOptions: [],
  userOptions: [
    {
      label: '个人中心',
      key: 'personal',
      icon: renderIcon(PersonCircleOutline)
    },
    {
      label: '退出登录',
      key: 'quit',
      icon: renderIcon(LogOutOutline)
    },
  ],
})

let showMenuDrawer = ref(false)
let showMenu = ref(document.body.clientWidth >= 1440)
onMounted(() => {
  window.onresize = () => {
    showMenuDrawer.value = false
    showMenu.value = document.body.clientWidth >= 1440
    mainStore.setPaginationSimple(document.body.clientWidth < 1440)
  }
  const iconArr = [
    { name: 'dashboard', icon: HomeOutline },
    { name: 'carmi', icon: KeyOutline },
  ]

  const renderMenu = list => {
    const renderIcon = name => {
      const { icon } = iconArr.filter(item => item.name === name)[0] || { icon: null }
      return () => h(NIcon, { component: icon }, {})
    }
    const handleField = item => {
      return {
        label: item.meta.title,
        key: item.name,
        icon: item.meta.icon && renderIcon(item.name),
        children: item.children && renderMenu(item.children),
      }
    }
    return list.map(item => handleField(item))
  }
  // 侧边菜单栏
  centerData.menuOptions = renderMenu(menuRoutes)
})

const switchMenu = key => {
  showMenuDrawer.value = false
  router.push({ name: key })
}

const personalState = reactive({
  showPersonalDrawer: false,
  changing: false,
  editPasswordForm: {
    password: '',
    newPassword: ''
  },
  passwordRules: {
    password: { required: true, message: '请输入旧密码', trigger: 'input' },
    newPassword: {
      required: true,
      validator(rule, value) {
        if (!value) return new Error('请输入新密码')
        if (value.length < 6 || value.length > 18) return new Error('密码长度必须在6至18位')
        return true
      },
      trigger: 'input',
    }
  }
})

const selectUserMenu = key => {
  switch (key) {
    case 'personal':
      personalState.showPersonalDrawer = true
      break
    case 'quit':
      userStore.logout()
      break
  }
}

const submitEditPassword = async () => {
  proxy.$refs.editPwdFormRef.validate(async validate => {
    if (validate) return false
    try{
      personalState.changing = true
      const res = await changePass(personalState.editPasswordForm)
      if(res.statusCode !== 200){
        personalState.changing = false
        return false
      }
      $message.success(res.message+'，正在退出登录。。。')
      setTimeout(()=>{
        userStore.logout()
      },1000)
    } catch {
      personalState.changing = false
    }
  })
}
</script>

<style lang="less" scoped>
.center-container {
  height: 100vh;

  &:deep(.menu-drawer) {
    .n-drawer-body {
      .n-drawer-body-content-wrapper {
        padding: 0;
      }
    }
  }

  &:deep(.n-layout-sider),
  &:deep(.menu-drawer) {
    .sider-logo {
      .logo-content {
        width: 100%;
        height: 100%;
        background-color: hsla(0, 0%, 100%, .1) !important;

        .n-text {
          color: hsla(0, 0%, 100%, .75) !important;
        }
      }
    }

    .n-menu {
      padding: 14px;
      .n-menu-item,
      .n-submenu {
        .n-menu-item-content {
          user-select: none;

          &:before,
          &:after {
            right: 0;
          }

          &:before {
            left: 0;
          }
        }

        .n-menu-item-content:not(.n-menu-item-content--disabled).n-menu-item-content--hover::before,
        .n-menu-item-content:not(.n-menu-item-content--disabled):hover::before {
          background: var(--n-item-color-active);
        }

        .n-menu-item-content.n-menu-item-content--selected {
          &:before {
            border-radius: 6px;
          }

          &:after {
            background-color: var(--n-item-text-color-active);
          }

          .n-menu-item-content__icon,
          .n-menu-item-content-header {
            color: var(--n-item-text-color-active);
          }
        }
      }
    }

    .n-layout-toggle-button {
      width: 32px;
      height: 32px;
      border: 5px solid #ffffff;

      .n-base-icon {
        background-color: var(--n-item-text-color-active);
        color: #ffffff;
        border-radius: 50%;
        font-size: 20px;
      }
    }
  }


  &:deep(.main-layout) {
    position: relative;

    .n-scrollbar-content {
      .header-container {
        width: 100%;
        padding-bottom: 0;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;

        .n-layout-header {
          max-width: 1400px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 0 auto;
        }
      }

      .main-content {
        height: calc(100vh - 80px);

        .n-layout-scroll-container {
          .content-container {
            max-width: 1448px;
            min-height: calc(100vh - 80px);

            .n-data-table {
              height: calc(100vh - 185px);

              .n-data-table__pagination {
                justify-content: center;
              }
            }
          }
        }
      }

      @media only screen and (max-width: 640px) {
        .main-content {
          height: calc(100vh - 64px);

          .n-layout-scroll-container {
            .content-container {
              min-height: calc(100vh - 64px);

              .n-data-table {
                height: calc(100vh - 145px);
              }
            }
          }
        }
      }
    }
  }

  &:deep(.n-dropdown-menu) {
    .n-dropdown-option {
      .n-dropdown-option-body {
        padding-left: 15px;

        .n-dropdown-option-body__label {
          padding-top: 1px;

        }
      }
    }
  }
}</style>
